#!/bin/bash

# 定义变量
DEFAULT_DB="$HOME/.local/share/kylin-ai-vector-engine/default.db"
OLD_DEFAULT_DB="$HOME/.local/share/milvus-lite/default.db"
DB_NAME="$(basename "$DEFAULT_DB")"
SYSTEM_DB="/usr/share/kylin-ai-vector-engine/default.db"
BIN="/usr/bin/kylin-ai-vector-engine"
WORK_DIR="$(dirname "$DEFAULT_DB")"
SAFE_DEFAULT_DB=$(echo "$DEFAULT_DB" | sed 's/\//_/g') # 将所有斜杠替换为下划线
LOCK_FILE="${TMPDIR:-/tmp}/kylin-ai-vector-engine-${SAFE_DEFAULT_DB}-$(id -u).lock"
UDS_PATH="${TMPDIR:-/tmp}/kylin-ai-vector-engine-$(id -u).sock"
LOG_LEVEL="${LOG_LEVEL:-ERROR}"

echo "Starting Kylin AI Vector Engine Service..."
echo "DEFAULT_DB: $DEFAULT_DB"
echo "UDS_PATH: $UDS_PATH"
echo "LOCK_FILE: $LOCK_FILE"
echo "LOG_LEVEL: $LOG_LEVEL"

# 检查DEFAULT_DB是否符合要求
if ! [[ "$DB_NAME" =~ ^[a-zA-Z0-9.\-_]+$ ]]; then
    echo "Unsupport db name $(basename "$DEFAULT_DB"), the name must match ^[a-zA-Z0-9.\-_]+$"
    exit 1
fi

if [ ${#DB_NAME} -gt 36 ]; then
    echo "Db name $(basename "$DEFAULT_DB") is too long, should be less than 36"
    exit 1
fi

# 检查WORK_DIR是否存在
if [ ! -d "$WORK_DIR" ]; then
    echo "Dir $WORK_DIR not exist, creating it..."
    mkdir -p "$WORK_DIR"
    if [ $? -eq 0 ]; then
        echo "Dir $WORK_DIR created successfully."
    else
        echo "Failed to create dir $WORK_DIR."
        exit 1
    fi
fi

if [ ! -f "$DEFAULT_DB" ]; then
    echo "New default DB $DEFAULT_DB not found, attempting upgrade migration..."

    # 先尝试从旧版本数据库迁移
    if [ -f "$OLD_DEFAULT_DB" ]; then
        echo "Found legacy DB $OLD_DEFAULT_DB, migrating to new location..."
        mkdir -p "$(dirname "$DEFAULT_DB")"
        if cp "$OLD_DEFAULT_DB" "$DEFAULT_DB"; then
            echo "Successfully migrated legacy DB to $DEFAULT_DB"

            # 迁移后删除旧数据库
            rm "$OLD_DEFAULT_DB"
        else
            echo "[ERROR] Failed to copy legacy DB from $OLD_DEFAULT_DB" >&2
            exit 1
        fi

    # 旧版本也不存在时，从系统默认初始化
    else
        echo "No legacy DB found at $OLD_DEFAULT_DB, initializing from system default..."
        mkdir -p "$(dirname "$DEFAULT_DB")"
        if cp "$SYSTEM_DB" "$DEFAULT_DB"; then
            echo "Successfully initialized default DB from system template"
        else
            echo "Failed to initialize DB from $SYSTEM_DB"
            exit 1
        fi
    fi
fi

#获取锁
exec {LOCK_FD}>"$LOCK_FILE"
if ! flock -n "$LOCK_FD"; then
    echo "Open $DEFAULT_DB failed, the file has been opened by another program"
    exit 1
fi

# 启动服务
"$BIN" "$DEFAULT_DB" "unix:$UDS_PATH" "$LOG_LEVEL" &

# 保存进程ID
PID=$!

# 注册信号处理函数
function cleanup {
    echo "Stopping Kylin AI Vector Engine Service..."
    kill -TERM "$PID" 2>/dev/null
    wait "$PID" 2>/dev/null
    rm -f "$UDS_PATH" "$LOCK_FILE"
    echo "Kylin AI Vector Engine Service stopped."
    exit 0
}

trap cleanup EXIT

# 等待服务停止
wait "$PID"
